import './App.css';
import React from 'react';
import LineHeight2 from './LineHeight2';
import LineWeight2 from './LineWeight2';
import LineHead2 from './LineHead2';
import { List, Tabs, WhiteSpace, WingBlank, Card, Calendar, Button, Toast, Accordion, NoticeBar, Flex, Badge } from 'antd-mobile';
import moment from 'moment';
import * as request from './request';
import Toolbar from "./Toolbar";
import { connect } from 'react-redux';
import Header from "./Header";

const tabs = [
  { title: '身高' },
  { title: '体重' },
  { title: '头围' },
];
const Item = List.Item;
const Brief = Item.Brief;
const now = new Date();
const apiURL = "/api/services/app/Edu_EventGrowth/GetList?SkipCount=0&MaxResultCount=100";
const apiBzUrl = "/api/services/app/Edu_PrematureBabyCurve/GetList";
const apiURLChild = "/api/services/app/Edu_Children/Get?id=";
const apiURLBMI = "/api/services/app/Edu_BMI/GetAll?skipCount=0&maxResultCount=200";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      growthData: [],
      growthBzData: [],
      babyData: {
        weight: 0,
        gweek: 0,
        correctGestionalAge: 0,
        correctAge: 0
      },
      show: false,
      config: {
        type: 'one'
      },
      startTime: now,
      dataBMI: []
    }
  }
  componentDidMount() {
    var memberId = localStorage.getItem('memberId');
    if (!memberId) {
      Toast.info('请先登录');
      this.props.history.push('/Login');
    }
    else {
      this.fetchBMI();
      this.fetchData();
    }
  }
  fetchData = () => {
    var cid = this.props.match.params.childid;
    const childid = localStorage.getItem('childid');
    cid = cid === undefined ? (childid ? childid : null) : cid;
    this.getBabyData(cid)
  }

  getBabyData = (cid) => {
    if (cid) {
      var apiurl = apiURL + '&childId=' + cid + '&eType=basic';
      request.get(apiURLChild + cid).then((data) => {
        var babyData = data.result;
        this.setState({ babyData });
        request.get(apiurl)
          .then((data) => {
            var minAge = 99999;
            var maxAge = 0;
            var growthData = data.result.items
            var sex = babyData.sex === "男" ? 1 : 0;
            var btype = babyData.correctGestionalAge < 40 ? 0 : 1; //早产儿是0
            this.setState({ growthData });
            if (btype === 0) {
              minAge = 0;
              maxAge = 50;
            }
            else {
              minAge = 0;
              maxAge = 36;
            }
            request.get(apiBzUrl + "?sex=" + sex + "&btype=" + btype + "&minAge=" + minAge + "&maxAge=" + maxAge).then((response) => {
              var growthBzData = response.result.items;
              this.setState({ growthBzData });
            });

          })
      });
    }
    else {
      Toast.info('请选择宝宝');
    }
  }

  onSelectHasDisableDate = (dates) => {
    console.warn('onSelectHasDisableDate', dates);
  }

  onConfirm = (startTime, endTime) => {
    document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
    this.setState({
      show: false,
      startTime,
      endTime,
    });
  }

  onCancel = () => {
    document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
    this.setState({
      show: false,
      startTime: undefined,
      endTime: undefined,
    });
  }
  fetchBMI = () => {
    request.get(apiURLBMI).then((data) => {
      this.setState({ dataBMI: data.result.items });
    })
  }
  selectBaby = (babyData) => {
    this.setState({ babyData })
    this.getBabyData(babyData.id)
  }
  render() {
    const { growthData, growthBzData, babyData, dataBMI } = this.state;
    const age = request.getAge(moment(babyData.birthday).format("YYYY-MM-DD"));
    const sex = babyData.sex === "男" ? 1 : 0
    return (
      <div className="App">
        <Header state={this.props} selectBaby={this.selectBaby} />
        <WhiteSpace size="md" />
        <WingBlank size="md">
          <Accordion className="my-accordion">
            <Accordion.Panel header={babyData.name + ' ' + (sex == 1 ? '男孩' : '女孩') + ' ' + age}>
              <List className="my-list">
                <Item extra={babyData.name}>宝宝姓名：</Item>
                <Item extra={babyData.gweek + ' 周'}>宝宝胎龄：</Item>
                <Item extra={moment(babyData.birthday).format("YYYY-MM-DD")}>出生日期：</Item>
                <Item extra={babyData.sex === '女' ? '女宝宝' : '男宝宝'}>宝宝性别：</Item>
                <Item extra={babyData.weight + ' kg'}>宝宝体重：</Item>
                <Item extra={(babyData.gweek < 40 ? babyData.correctGestionalAge : babyData.correctAge) + (babyData.gweek < 40 ? " 周" : " 月")}>{babyData.gweek < 40 ? "纠正胎龄：" : "纠正月龄："}</Item>

              </List>
            </Accordion.Panel>
          </Accordion>

          <WhiteSpace size="md" />
          <Card title="Fenton生长曲线">
            <NoticeBar mode="closable" icon={null}>Fenton生长曲线是2013年由国外专家根据胎儿在子宫内生长规律制定的早产儿生长曲线图，也是我国近年来医院通用的、用来监测早产儿生长发育状况的一个常用标准曲线。</NoticeBar>
            <Card.Body style={{ padding: 5, margin: 0 }}>
              <Tabs tabs={tabs}
                initialPage={1}
                onChange={(tab, index) => { }}
                onTabClick={(tab, index) => { }}
              >
                <div>
                  <WhiteSpace />
                  <LineHeight2 growthData={growthData} growthBzData={growthBzData} babyData={babyData} />
                </div>
                <div>
                  <WhiteSpace />
                  <LineWeight2 growthData={growthData} growthBzData={growthBzData} babyData={babyData} />
                </div>
                <div>
                  <WhiteSpace />
                  <LineHead2 growthData={growthData} growthBzData={growthBzData} babyData={babyData} />
                </div>
              </Tabs>
              <NoticeBar>{'宝宝胎龄>=40周以月为单位，<40周以周单位'}</NoticeBar>
            </Card.Body>
          </Card>
          <WhiteSpace size="md" />
          <Button type="primary" onClick={() => this.props.history.push('/RecGrowth/0')}>点我记录</Button>
          <WhiteSpace size="md" />
          <Card style={{ marginBottom: 80 }}>
            <Card.Body style={{ padding: 2 }}>
              <NoticeBar>{'BMI是指人体质量指数，判断人体健康标准之一'}</NoticeBar>
              <List renderHeader={() => '生长记录'} className="my-list">
                {
                  growthData.map((i, index) => {
                    let bmi = request.getBMI(i.weight, i.height)
                    let bmiNote = request.noteBMI(bmi, i.ageMonth, dataBMI, sex)
                    return (
                      <Item
                        multipleLine
                        onClick={() => { }}
                        platform="android"
                        key={index}
                      >
                        {moment(i.eventDate).format("YYYY-MM-DD")}
                        <Brief>宝宝在{i.ageWeek + '周'}{i.ageMonth + '月'}时的生长指数:  </Brief>
                        <Flex>
                          <Flex.Item><Brief>身高：{i.height}cm</Brief></Flex.Item>
                          <Flex.Item><Brief>体重：{i.weight}kg</Brief></Flex.Item>
                        </Flex>
                        <Flex>
                          <Flex.Item><Brief>头围：{i.headCirc}cm</Brief></Flex.Item>
                          <Flex.Item><Brief>BMI: {bmi} <Badge text={bmiNote} style={{ backgroundColor: '#' + (bmiNote == '正常' ? '4CAF50' : 'F44336') }} /></Brief></Flex.Item>
                        </Flex>
                      </Item>
                    )
                  })
                }
              </List>
            </Card.Body>
          </Card>

        </WingBlank>
        <Calendar
          {...this.state.config}
          visible={this.state.show}
          onCancel={this.onCancel}
          onConfirm={this.onConfirm}
          onSelectHasDisableDate={this.onSelectHasDisableDate}
          defaultDate={now}
          minDate={new Date(+now - 5184000000)}
          maxDate={new Date(+now + 31536000000)}
        />
        <Toolbar history={this.props.history} selectedTab='Growth' />
      </div>
    )
  };
}
export default connect(
  state => ({ currentUser: state.setCurrentUser, currentChild: state.setCurrentChild })
)(App)
